<template>
  <n-menu
    :options="menuOptions"
    :default-expanded-keys="defaultExpandedKeys"
    :collapsed="collapsed"
    :collapsed-width="50"
    :collapsed-icon-size="22"
    :value="currentSpace"
    @update:value="changeSpace"
  />
</template>

<script setup lang='ts'>
import {ref,h, Component, onMounted, computed} from "vue"
import { NIcon } from 'naive-ui'
import {getUserJoinSpace, getUserCreateSpace} from "../api/space"
import { useRouter } from "vue-router";
const router = useRouter()

import {
  Apps,
  BagOutline as BagOutlineIcon
} from '@vicons/ionicons5'

defineProps<{
  collapsed: boolean
}>()

function renderIcon (icon: Component) {
  return () => h(NIcon, null, { default: () => h(icon) })
}

const defaultExpandedKeys = ref(['addSpace'])
let menuOptions:any = ref([
  {
    label: '创建的空间',
    key: 'createSpace',
    icon: renderIcon(BagOutlineIcon),
    children: [
      // {
      //   label: '无',
      //   key: 'can-not'
      // }
    ]
  },
  {
    label: '加入的空间',
    key: 'addSpace',
    icon: renderIcon(Apps),
    children: [
      
    ]
  },
])

type childrenType = {
  label: string,
  key: string
}
type spaceType = {
  space_name: string,
  space_id: string
}

const changeSpace = (key:string) => {
  emits("joinSpaceData", key)
  // router.push("/home/spaceHome/" + key)
}

onMounted(async () => {
  const phone = localStorage.getItem("token") || ""
  const join_res = await getUserJoinSpace(phone)
  if(join_res.code!="200"){
    // window.$message.warning(join_res.message)
  }else{
    join_res.data.forEach((e:spaceType) => {
      let children:childrenType = {
        label: e.space_name,
        key: e.space_id
      }
      menuOptions.value[1].children.push(children)
    })
  }

  const create_res = await getUserCreateSpace(phone)
  if(create_res.code!="200"){
    // window.$message.warning(create_res.message)
  }else{
    create_res.data.forEach((e:spaceType) => {
      let children:childrenType = {
        label: e.space_name,
        key: e.space_id
      }
      menuOptions.value[0].children.push(children)
    })
  }

  if(join_res.data[0]){
    if(router.currentRoute.value.params.spaceId){
      emits("joinSpaceData", router.currentRoute.value.params.spaceId as string)
    }else{
      emits("joinSpaceData", join_res.data[0]?.space_id)
    }
  }else if(create_res.data[0]){
    if(router.currentRoute.value.params.spaceId){
      emits("joinSpaceData", router.currentRoute.value.params.spaceId as string)
    }else{
      emits("joinSpaceData", create_res.data[0]?.space_id)
    }
  }else{
    emits("joinSpaceData", "0")
  }
})

const emits = defineEmits<{
  joinSpaceData: [defaultId:string],
}>()

const currentSpace = computed(() => {
  return Number(router.currentRoute.value.params.spaceId)
})

  
</script>

<style lang='scss' scoped>
  
</style>